package com.bridge.netty.utils;

import java.nio.charset.Charset;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AESCrypt  {
	private static final Logger log = LoggerFactory.getLogger(AESCrypt.class);

	protected String algorithm = "AES";
	protected Charset charset = Charset.forName("UTF-8");
	protected String aesKey;
	
	public AESCrypt(String aesKey, Charset charset) {
		this.aesKey = aesKey;
		this.charset = charset;
	}

	public AESCrypt(String aesKey) {
		this.aesKey = aesKey;
	}

	public AESCrypt() {
	}

	public byte[] encrypt(String secretKey, byte[] content) {
		try {
			Cipher aesECB = Cipher.getInstance("AES/ECB/PKCS5Padding");
			SecretKeySpec key = new SecretKeySpec(Base64.decode(secretKey), algorithm);
			aesECB.init(Cipher.ENCRYPT_MODE, key);
			return aesECB.doFinal(content);
		} catch (Exception e) {
			log.error(e.getMessage() + ",key:" + secretKey, e);
			throw new RuntimeException( " 加密失败  " );  
		}
	}


	public byte[] decrypt(String secretKey, byte[] content) {
		try {
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 创建密码器
			SecretKeySpec key = new SecretKeySpec(Base64.decode(secretKey), algorithm);
			cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
			return cipher.doFinal(content); // 解密
		} catch (Exception e) {
			log.error(e.getMessage() + ",key:" + secretKey, e);
			throw new RuntimeException( " 解密失败  " );  
		}
	}



	
}
